package com.daiyang;

import com.daiyang.common.pojo.Result;
import com.daiyang.common.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    //private List<String> urlWhiteName =List.of("/user/login","/user/register");

    @Autowired
    private AuthWhiteNameProperties authWhiteName;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(match(path,authWhiteName.getUrl())){
            //白名单，直接放行
            return chain.filter(exchange);
        }

        String userToken =request.getHeaders().getFirst("user_token");
        log.info("user_token:"+userToken);
        if(StringUtils.isEmpty(userToken)){
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Integer userId = JWTUtils.getUserIdFromToken(userToken);
        if (userId==null){
            return unauthorizedResponse(exchange, "令牌已过期或者不合法");
        }
        return chain.filter(exchange);

    }

    private boolean match(String path, List<String> urls) {
        if(CollectionUtils.isEmpty(urls)){
            return false;
        }
        return urls.contains(path);
    }

    @SneakyThrows
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange,String msg) {
        log.error("[⽤⼾⾝份认证异常] 请求路径: {}", exchange.getRequest().getPath());
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        Result result =Result.fail(msg);
        DataBuffer dataBuffer =
                response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -200;//值越小，优先级越高
    }
}
